package com.github.ghsea.dbtracer.db;

import java.util.concurrent.atomic.AtomicInteger;

import com.github.ghsea.dbtracer.util.IpUtil;

public class TransactionIdUtil {

	private static AtomicInteger sequence = new AtomicInteger(-1);

	private static int LENGTH_MAX_INT = 10;
	private static int LENGTH_MAX_LONG = 20;

	private static String formatedIp;

	/**
	 * 左20位(由当前时间戳左位补0而来)+左10位(由于sequence左位补0而来)+12位本机IP地址(去点号并补0而来)
	 * 
	 * @return
	 */
	public static String nextTransactionId() {
		sequence.compareAndSet(Integer.MIN_VALUE, -1);
		int num = sequence.incrementAndGet();
		String num10 = paddingLeft(String.valueOf(num), LENGTH_MAX_INT);
		String time = paddingLeft(String.valueOf(System.currentTimeMillis()), LENGTH_MAX_LONG);

		StringBuffer txId = new StringBuffer(42);
		txId.append(time).append(num10).append(getFormatedIp());
		return txId.toString();
	}

	private static String paddingLeft(String num, int length) {
		if (num.length() == length) {
			return num;
		}
		StringBuffer sb = new StringBuffer(length);
		int padCount = length - num.length();
		for (int idx = 0; idx < padCount; idx++) {
			sb.append('0');
		}
		sb.append(num);
		return sb.toString();
	}

	private static String getFormatedIp() {
		if (formatedIp == null) {
			String ip = IpUtil.getLocalIp();
			String[] splitedIps = ip.split("\\.");
			StringBuffer fIp = new StringBuffer(12);
			for (int idx = 0; idx < splitedIps.length; idx++) {
				fIp.append(paddingLeft(splitedIps[idx], 3));
			}
			formatedIp = fIp.toString();
		}
		return formatedIp;
	}

	public static void main(String[] args) {
		long s = System.currentTimeMillis();
		for (int idx = 0; idx < 100000; idx++) {
			nextTransactionId();
		}
		long e = System.currentTimeMillis();
		System.out.println(e-s);
		System.out.println(nextTransactionId().length());
	}
}
